﻿/// Created by Michael Nemtsev
/// http://msmvps.com/blogs/laflour

#region

using System;
using System.Web;
using System.Web.Configuration;
using Microsoft.SharePoint;

#endregion

namespace SharePoint403Module
{
    public class Custom403PageModule : IHttpModule
    {
        #region Fields

        public const string ACCESS_DENIED_PAGE = "/_layouts/accessdenied.aspx";
        public readonly string REDIRECT_TO = WebConfigurationManager.AppSettings["SPCustom403PageUrl"];

        #endregion

        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.EndRequest += (context_EndRequest);
        }

        #endregion

        private void context_EndRequest(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(REDIRECT_TO)) return;

            var application = sender as HttpApplication;
            if (application != null)
            {
                try
                {
                    // ignoring "sign-in as different user" action (SharePoint redirects you to AccessDenied page, but with the parameters in url)
                    if (application.Context.Request.Url.ToString().ToLower().Contains("loginasanotheruser")) return;

                    if (application.Context.Request.Url.ToString().ToLower().Contains(ACCESS_DENIED_PAGE) &&
                        application.Context.Response.StatusCode == 200) // ignore unauthorized and other errors
                    {
                        HttpContext.Current.Server.ClearError();
                        HttpContext.Current.Response.Clear();
                        HttpContext.Current.Response.Redirect(REDIRECT_TO, false);
                    }
                }
                catch (Exception ex)
                {
                    // yummy-yummy
                }
            }
        }
    }
}